const Base = require('./base.js');
const nodemailer = require('nodemailer');
const randomstring = require('randomstring');
const { think } = require('thinkjs');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const data = await this.model('company_list')
      .order(['id DESC'])
      .alias('a')
      .join({
        industry_list: {
          join: 'left',
          as: 'i',
          on: ['industry', 'id'],
        },
      })
      .where({
        is_auth: 2,
        'a.name': ['!=', null],
        'a.avatar': ['!=', null],
        'a.status': 0,
      })
      .field('i.name as industry_name, a.*')
      .page(page, size)
      .countSelect();

    return this.success(data);
  }
  async detailAction() {
    const data = await this.model('company_list')
      .where({ 'a.id': this.get('id') })
      .alias('a')
      .join({
        industry_list: {
          join: 'left',
          as: 'i',
          on: ['industry', 'id'],
        },
      })
      .field('i.name as industry_name, a.*')
      .find();

    if (data.img) {
      data.imgs = data.img.split(',');
    }

    const jobList = await this.model('company_job')
      .where({
        company_id: data.id,
      })
      .distinct('job_id')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'j',
          on: ['job_id', 'id'],
        },
      })
      .field('j.*, a.company_id')
      .select();
    if (!think.isEmpty(jobList)) {
      data.jobList = await this.model('index').getJobInfo(jobList);
    }
    if (data.fuli) {
      data.tags = await this.model('tag_list')
        .where({
          id: ['IN', data.fuli],
        })
        .field('name, icon')
        .select();
    }

    return this.success(data);
  }
  async jobAction() {
    const job = await this.model('company_job')
      .where({
        company_id: this.get('company'),
        job_id: this.get('id'),
      })
      .distinct('job_id')
      .alias('a')
      .join({
        company_list: {
          join: 'left',
          as: 'c',
          on: ['company_id', 'id'],
        },
        industry_list: {
          join: 'left',
          as: 'i',
          on: ['c.industry', 'id'],
        },
      })
      .field(
        'c.fuli, a.need, c.avatar, c.name, a.company_id, i.name as industry_name, c.scale, c.city, c.id, a.city_name as job_city, a.work_time_start, a.work_time_end'
      )
      .find();
    if (think.isEmpty(job)) {
      return this.success(null);
    }

    if (job.fuli) {
      job.tags = await this.model('tag_list')
        .where({
          id: ['IN', job.fuli],
        })
        .field('name, icon')
        .select();
    }

    return this.success(job);
  }
};
